package com.yinhe.controller.jibeiSync;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.yinhe.model.*;
import com.yinhe.model.jibeiPO.*;
import com.yinhe.service.jibeiSync.IJiBeiMTParseService;
import com.yinhe.service.jibeiSync.IJiBeiService;
import com.yinhe.util.RedisUtils;
import com.yinhe.util.jibeiSync.DateTimeUtil;
import com.yinhe.util.jibeiSync.redisListJsonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName JiBeiDataFromFileController
 * @Description
 * @Author xiaolongZzz66
 * @Time 2023/12/8 13:52
 * @Version 1.0
 */

@RestController
@Slf4j
@RequestMapping("/anfenByFile")
@Api(tags = "冀北-安分-文件解析数据（直接通过读取文件获取）")
public class JiBeiDataFromFileController {

    @Autowired
    private IJiBeiService iJiBeiService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private IJiBeiMTParseService jiBeiMTParseService;

    /**
     * 获取多路短路比(xiaolong66-)不需要改程序
     * @return
     * @throws Exception
     */
    @ApiOperation("获取多路短路比")
    @RequestMapping(value = "/getXNY", produces = "application/json; charset=utf-8", method = RequestMethod.GET)
    public List<DSA_XNY_DLB_UN_PO> getXNY() throws Exception {
        log.info("获取-多路短路比开始");
        List<DSA_XNY_DLB_UN_PO> dsa_xny_dlb_un_poList = new ArrayList<>();
        try {
            List<String> today96Point = redisUtils.getList("TODAY96POINT");
            if (today96Point==null){
                today96Point = DateTimeUtil.getToday96Point();
            }
            LocalDateTime now = LocalDateTime.now();
            List<String> nowAllPoint = today96Point.stream().filter(s ->  DateTimeUtil.IsoStringToLocateDate(s).isBefore(now)).collect(Collectors.toList());
            for (String itemPoint : nowAllPoint) {
                List<DSA_XNY_DLB_UN_PO> dsa_xny_dlb_un_pos = iJiBeiService.selectXNY("XNY.res", "DSA_XNY_DLB_UN", itemPoint);
                if(dsa_xny_dlb_un_pos!=null&&dsa_xny_dlb_un_pos.size()>0){
                    dsa_xny_dlb_un_poList.addAll(dsa_xny_dlb_un_pos);
                }
            }
        } catch (Exception e) {
            log.error("获取多路短路比失败：原因如下：" + e.getMessage());
        }
        return dsa_xny_dlb_un_poList;
    }


    /**
     * 新能源多路短路比(全部场站数据)
     * @return
     * @throws Exception
     */
    @ApiOperation("获取多路短路比")
    @RequestMapping(value = "/getXNYAllPosition", produces = "application/json; charset=utf-8", method = RequestMethod.GET)
    public List<DSA_XNY_DLB_UN_PO> selectXNYAllPosition() throws Exception {
        log.info("获取-多路短路比开始");
        List<DSA_XNY_DLB_UN_PO> dsa_xny_dlb_un_poList = new ArrayList<>();
        try {
            List<String> today96Point = redisUtils.getList("TODAY96POINT");
            if (today96Point==null){
                today96Point = DateTimeUtil.getToday96Point();
            }
            LocalDateTime now = LocalDateTime.now();
            List<String> nowAllPoint = today96Point.stream().filter(s ->  DateTimeUtil.IsoStringToLocateDate(s).isBefore(now)).collect(Collectors.toList());
            for (String itemPoint : nowAllPoint) {
                List<DSA_XNY_DLB_UN_PO> dsa_xny_dlb_un_pos = iJiBeiService.selectXNYAllPosition("XNY.res", "DSA_XNY_DLB_UN", itemPoint);
                if(dsa_xny_dlb_un_pos!=null&&dsa_xny_dlb_un_pos.size()>0){
                    dsa_xny_dlb_un_poList.addAll(dsa_xny_dlb_un_pos);
                }
            }
        } catch (Exception e) {
            log.error("获取多路短路比失败：原因如下：" + e.getMessage());
        }
        return dsa_xny_dlb_un_poList;
    }


    /**
     * 稳定裕度分析
     * @return
     * @throws Exception
     */
    @ApiOperation("稳定裕度分析")
    @RequestMapping(value = "/getPhase", produces = "application/json; charset=utf-8", method = RequestMethod.GET)
    public List<TTCOutput_PO> getPhase() throws Exception {
        List<TTCOutput_PO> ttcOutput_poList = new ArrayList<>();
        try {
            log.info("获取-稳定裕度分析");
            List<String> today96Point = redisUtils.getList("TODAY96POINT");
            if (today96Point==null){
                today96Point = DateTimeUtil.getToday96Point();
            }
            LocalDateTime now = LocalDateTime.now();
            List<String> nowAllPoint = today96Point.stream().filter(s ->  DateTimeUtil.IsoStringToLocateDate(s).isBefore(now)).collect(Collectors.toList());
            for (String itemPoint : nowAllPoint) {
                List<TTCOutput_PO> ttcOutputs = iJiBeiService.selectPhase("phase2.res", "TTCOutput", itemPoint);
                if(ttcOutputs!=null&&ttcOutputs.size()>0){
                    ttcOutput_poList.addAll(ttcOutputs);
                }
            }

        } catch (Exception e) {
            log.error("稳定裕度分析失败：原因如下：" + e.getMessage());
        }
        return ttcOutput_poList;
    }


    /**
     * 静态安全分析-- 最大越限百分比
     * @return
     * @throws Exception
     */
    @ApiOperation("静态安全分析-- 最大越限百分比")
    @RequestMapping(value = "/getPSQSOutLimitRate", produces = "application/json; charset=utf-8", method = RequestMethod.GET)
    public List<SAOUT_OVER_PO> getPSQSOutLimitRate() throws Exception {
        List<SAOUT_OVER_PO> saoutOverPoList = new ArrayList<>();
        try {
            log.info("获取-静态安全分析-- 最大越限百分比");
            List<String> today96Point = redisUtils.getList("TODAY96POINT");
            if (today96Point==null){
                today96Point = DateTimeUtil.getToday96Point();
            }
            LocalDateTime now = LocalDateTime.now();
            List<String> nowAllPoint = today96Point.stream().filter(s ->  DateTimeUtil.IsoStringToLocateDate(s).isBefore(now)).collect(Collectors.toList());
            for (String itemPoint : nowAllPoint) {
                List<SAOUT_OVER_PO> saoutOverPos = iJiBeiService.selectPSQSOutLimitRate("PSASP_STCRIT.QS", "SAOUT_OVER", itemPoint);
                if(saoutOverPos!=null&&saoutOverPos.size()>0){
                    saoutOverPoList.addAll(saoutOverPos);
                }
            }
        } catch (Exception e) {
            log.error("最大越限百分比失败：原因如下：" + e.getMessage());
        }
        return saoutOverPoList;
    }


    /**
     * 静态安全分析NEW最新 -- 最大越限百分比NEW（xiaolong66）
     * @return
     * @throws Exception
     */
    @ApiOperation("NEW静态安全分析NEW最新---最大越限百分比NEW（最小安全裕度分析NEW）")
    @RequestMapping(value = "/getPSQSOutLimitNEWRate", produces = "application/json; charset=utf-8", method = RequestMethod.GET)
    public List<GD_SAOUT_PO> getPSQSOutLimitNEWRate() throws Exception {
        List<GD_SAOUT_PO> saoutOverPoList = new ArrayList<>();
        try {
            log.info("获取-静态安全分析NEW最新-- 最大越限百分比NEW（最小安全裕度分析NEW）");
            List<String> today96Point = redisUtils.getList("TODAY96POINT");
            if (today96Point==null){
                today96Point = DateTimeUtil.getToday96Point();
            }
            LocalDateTime now = LocalDateTime.now();
            List<String> nowAllPoint = today96Point.stream().filter(s ->  DateTimeUtil.IsoStringToLocateDate(s).isBefore(now)).collect(Collectors.toList());
            for (String itemPoint : nowAllPoint) {
                List<GD_SAOUT_PO> saoutOverPos = iJiBeiService.
                        selectGDSAOUTLimitRate("PSASP_STCRIT.QS", "GD_SAOUT", itemPoint);
                if(saoutOverPos!=null&&saoutOverPos.size()>0){
                    saoutOverPoList.addAll(saoutOverPos);
                }
            }
        } catch (Exception e) {
            log.error("最大越限百分比NEW（最小安全裕度分析NEW）-失败：原因如下：" + e.getMessage());
        }
        return saoutOverPoList;
    }


    /**
     * 暂态稳定分析--最大公交差、最低电压(两表合一，新增一个标识位（selfType），用来区分那条是最大功角差power，那条是最低电压voltage)
     * @return
     * @throws Exception
     */
    @ApiOperation("暂态稳定分析--最大公交差、最低电压(两表合一，新增一个标识位（selfType），用来区分那条是最大功角差power，那条是最低电压voltage)")
    @RequestMapping(value = "/getPSQSPowerAngleMax", produces = "application/json; charset=utf-8", method = RequestMethod.GET)
    public List<GD_STOUT_PO> getPSQSPowerAngleMax() throws Exception {
        List<GD_STOUT_PO> gd_stout_poList = new ArrayList<>();
        try {
            log.info("获取-暂态稳定分析--最大公交差、最低电压");
            List<String> today96Point = redisUtils.getList("TODAY96POINT");
            if (today96Point==null){
                today96Point = DateTimeUtil.getToday96Point();
            }
            LocalDateTime now = LocalDateTime.now();
            List<String> nowAllPoint = today96Point.stream().filter(s ->  DateTimeUtil.IsoStringToLocateDate(s).isBefore(now)).collect(Collectors.toList());
            for (String itemPoint : nowAllPoint) {
                List<GD_STOUT_PO> gd_stout_pos = iJiBeiService.selectPSQSPowerAngleMax("PSASP_STCRIT.QS", "GD_STOUT", itemPoint);
                if (gd_stout_pos!=null && gd_stout_pos.size()>0){
                    gd_stout_poList.addAll(gd_stout_pos);
                }
            }
        } catch (Exception e) {
            log.error("暂态稳定分析--最大公交差、最低电压失败：原因如下：" + e.getMessage());
        }
        return gd_stout_poList;
    }

    /**
     * 电压稳定分析xiaolong66
     * @return
     * @throws Exception
     */
    @ApiOperation("电压稳定分析")
    @RequestMapping(value = "/getPSQSVoltageStabilityAnaly", produces = "application/json; charset=utf-8", method = RequestMethod.GET)
    public List<GD_VSOUT_PO> getPSQSVoltageStabilityAnaly() throws Exception {
        List<GD_VSOUT_PO> gd_vsout_poList = new ArrayList<>();
        try {
            log.info("获取-电压稳定分析");
            List<String> today96Point = redisUtils.getList("TODAY96POINT");
            if (today96Point==null){
                today96Point = DateTimeUtil.getToday96Point();
            }
            LocalDateTime now = LocalDateTime.now();
            List<String> nowAllPoint = today96Point.stream().filter(s ->  DateTimeUtil.IsoStringToLocateDate(s).isBefore(now)).collect(Collectors.toList());
            for (String itemPoint : nowAllPoint) {
                List<GD_VSOUT_PO> vsout_pos = iJiBeiService.selectPSQSVoltageStabilityAnaly("PSASP_STCRIT.QS", "GD_VSOUT", itemPoint);
                if(vsout_pos!=null && vsout_pos.size()>0){
                    gd_vsout_poList.addAll(vsout_pos);
                }
            }
        } catch (Exception e) {
            log.error("电压稳定分析失败：原因如下：" + e.getMessage());
        }
        return gd_vsout_poList;
    }


    /**
     * 最低阻尼比-小干扰分析(xiaolong66)
     * @return
     * @throws Exception
     */
    @ApiOperation("最低阻尼比")
    @RequestMapping(value = "/getPSQSDampingMin", produces = "application/json; charset=utf-8", method = RequestMethod.GET)
    public List<SSTOUT_PO> getPSQSDampingMin() throws Exception {
        List<SSTOUT_PO> sstout_poList = new ArrayList<>();
        try {
            log.info("获取-最低阻尼比");
            List<String> today96Point = redisUtils.getList("TODAY96POINT");
            if (today96Point==null){
                today96Point = DateTimeUtil.getToday96Point();
            }
            LocalDateTime now = LocalDateTime.now();
            List<String> nowAllPoint = today96Point.stream().filter(s ->  DateTimeUtil.IsoStringToLocateDate(s).isBefore(now)).collect(Collectors.toList());
            for (String itemPoint : nowAllPoint) {
                List<SSTOUT_PO> sstout_pos = iJiBeiService.selectPSQSDampingMin("PSASP_STCRIT.QS", "SSTOUT", itemPoint);
                if (sstout_pos!=null && sstout_pos.size()>0){
                    sstout_poList.addAll(sstout_pos);
                }
            }
        } catch (Exception e) {
            log.error("最低阻尼比失败：原因如下：" + e.getMessage());
        }
        return sstout_poList;
    }


    /**
     * 最大短路电流
     * @return
     * @throws Exception
     */
    @ApiOperation("最大短路电流")
    @RequestMapping(value = "/getPSQSShortCircuitMax", produces = "application/json; charset=utf-8", method = RequestMethod.GET)
    public List<SCCOUT_PO> getPSQSShortCircuitMax() throws Exception {
        List<SCCOUT_PO> sccout_poList = new ArrayList<>();
        try {
            log.info("获取-最大短路电流");
            List<String> today96Point = redisUtils.getList("TODAY96POINT");
            if (today96Point==null){
                today96Point = DateTimeUtil.getToday96Point();
            }
            LocalDateTime now = LocalDateTime.now();
            List<String> nowAllPoint = today96Point.stream().filter(s ->  DateTimeUtil.IsoStringToLocateDate(s).isBefore(now)).collect(Collectors.toList());
            for (String itemPoint : nowAllPoint) {
                List<SCCOUT_PO> sccout_pos = iJiBeiService.selectPSQSShortCircuitMax("PSASP_STCRIT.QS", "SCCOUT", itemPoint);
                if(sccout_pos!=null&&sccout_pos.size()>0){
                    sccout_poList.addAll(sccout_pos);
                }
            }
        } catch (Exception e) {
            log.error("最大短路电流失败：原因如下：" + e.getMessage());
        }
        return sccout_poList;
    }


    /**
     * 最大短路电流(xiaolong66)
     * @return
     * @throws Exception
     */
    @ApiOperation("NEW最大短路电流NEW")
    @RequestMapping(value = "/getPSQSShortCircuitMaxNEW", produces = "application/json; charset=utf-8", method = RequestMethod.GET)
    public List<GD_SCCOUT_PO> getPSQSShortCircuitMaxNEW() throws Exception {
        List<GD_SCCOUT_PO> sccout_poList = new ArrayList<>();
        try {
            log.info("获取-最大短路电流NEW");
            List<String> today96Point = redisUtils.getList("TODAY96POINT");
            if (today96Point==null){
                today96Point = DateTimeUtil.getToday96Point();
            }
            LocalDateTime now = LocalDateTime.now();
            List<String> nowAllPoint = today96Point.stream().filter(s ->  DateTimeUtil.IsoStringToLocateDate(s).isBefore(now)).collect(Collectors.toList());
            for (String itemPoint : nowAllPoint) {
                List<GD_SCCOUT_PO> sccout_pos = iJiBeiService.selectPSQSShortCircuitMaxNEW("PSASP_STCRIT.QS", "GD_SCCOUT", itemPoint);
                if(sccout_pos!=null&&sccout_pos.size()>0){
                    sccout_poList.addAll(sccout_pos);
                }
            }
        } catch (Exception e) {
            log.error("最大短路电流NEW失败：原因如下：" + e.getMessage());
        }
        return sccout_poList;
    }

    /**
     * 光伏发电数据功率预测
     */
    @ApiOperation("获取光伏发电数据未来小时h功率预测")
    @RequestMapping(value = "/getWindAndSolar", produces = "application/json; charset=utf-8", method = RequestMethod.GET)
    public List<SOLAR_WIND_FBS_VO> getWindAndSolar(){

        List<SOLAR_WIND_FBS_VO> pos = new ArrayList<>();
        try {
            log.info("获取风能和光能小时h预期数据开始");
            pos = iJiBeiService.selectWindAndSolarForecast();
        } catch (Exception e) {
            log.error("获取光伏发电数据功率小时h预测失败：原因如下：" + e.getMessage());
        }
        log.info("获取风能和光能小时h预期数据成功结束");
        return pos;
    }



    /**
     * 读取风力和光能预测数据10h最新接入--2024-0320（分布式光伏+集中式光伏+风能）
     */
    @ApiOperation("获取光伏发电数据未来小时h功率预测")
    @RequestMapping(value = "/selectWindAndSolarForecastShortTimeNew", produces = "application/json; charset=utf-8", method = RequestMethod.GET)
    public List<SOLAR_WIND_FBS_VO> selectWindAndSolarForecastShortTimeNew(){

        List<SOLAR_WIND_FBS_VO> pos = new ArrayList<>();
        try {
            log.info("获取风能和光能小时h预期数据--最新提供文件--开始");
            pos = iJiBeiService.selectWindAndSolarForecastShortTimeNew();
        } catch (Exception e) {
            log.error("获取光伏发电数据功率小时h预测--最新提供文件--失败：原因如下：" + e.getMessage());
        }
        log.info("获取风能和光能小时h预期数据--最新提供文件--成功结束");
        return pos;
    }



    /**
     * 光伏发电数据功率预测未来10天
     */
    @ApiOperation("获取光伏发电数据未来10day功率预测")
    @RequestMapping(value = "/getWindAndSolarForecast10day", produces = "application/json; charset=utf-8", method = RequestMethod.GET)
    public List<SOLAR_WIND_VO> getWindAndSolarForecast10day(){




        List<SOLAR_WIND_VO> windPos = new ArrayList<>();
        try {
            log.info("获取光伏发电数据未来10day功率预测开始");
            windPos = iJiBeiService.selectWindAndSolarForecast10day();
        } catch (Exception e) {
            log.error("获取光伏发电数据未来10day功率预测失败：原因如下：" + e.getMessage());
        }
        log.info("获取光伏发电数据未来10day功率预测成功结束");
        return windPos;
    }

    @ApiOperation("冀北全网断面受阻预测gd_qwdmsz")
    @RequestMapping(value = "/getGDKBXNY", produces = "application/json; charset=utf-8", method = RequestMethod.GET)
    public List<GD_KBXNY> getGDKBXNY(){
        List<GD_KBXNY> gdKbxnyList = new ArrayList<>();
        try {
            log.info("冀北全网断面受阻预测开始");
            gdKbxnyList = iJiBeiService.selectGDKBXNY();
        } catch (Exception e) {
            log.error("冀北全网断面受阻预测失败：原因如下：" + e.getMessage());
        }
        log.info("冀北全网断面受阻预测结束");
        return gdKbxnyList;
    }


    /**
     * 读取redis
     * @param key
     * @return
     */
    @ApiOperation("读取redis")
    @RequestMapping(value = "/getRedisByKey/{key}",produces = "application/json; charset=utf-8", method = RequestMethod.GET)
    public String getRedisByKey(@PathVariable("key") String key){
        String s = (String) redisUtils.get(key);
        JSONObject json = new JSONObject();
        json.put("code", "200");
        json.put("msg", "查询成功");
        json.put("data", s);
        return json.toJSONString();
    }



    @ApiOperation("三相单相最大短路电流ceshi---test---单个")
    @RequestMapping(value = "/getXNYs2", produces = "application/json; charset=utf-8", method = RequestMethod.GET)
    public List<SCCOUT_PO> getXNYs2() throws JsonProcessingException {


        // Map<String,List<SCCOUT_PO>>
        // 遍历读取所有刻度文件
        String itemPoint ="2023_12_07T15_15_00";
        List<SCCOUT_PO> sccout_pos = iJiBeiService.selectPSQSShortCircuitMax("PSASP_STCRIT.QS", "SCCOUT", itemPoint);
        // List<String> jsonList = new ArrayList<>();
        // for (SCCOUT_PO sccout_po : sccout_pos) {
        //     ObjectMapper objectMapper = new ObjectMapper();
        //     // 将自定义对象序列化为JSON字符串
        //     String jsonString = objectMapper.writeValueAsString(sccout_po);
        //     jsonList.add(jsonString);
        // }
        List<String> jsonList = redisListJsonUtil.objectTOJson(sccout_pos);
        redisUtils.setList("SCCOUT",jsonList );

        List<String> sccout = redisUtils.getList("SCCOUT");
        // ObjectMapper objectMapper = new ObjectMapper();
        // List<SCCOUT_PO> list = new ArrayList<>();
        // for (String jsonString: sccout) {
        //     SCCOUT_PO sccout_po = objectMapper.readValue(jsonString, SCCOUT_PO.class);// 反序列化为自定义对象
        //     list.add(sccout_po);
        // }
        List<SCCOUT_PO> sccout_pos1 = redisListJsonUtil.jsonToObject(sccout, SCCOUT_PO.class);
        return sccout_pos1;
    }

    @ApiOperation("冀北煤炭文件解析")
    @RequestMapping(value = "/getMT", produces = "application/json; charset=utf-8", method = RequestMethod.POST)
    public List<JB_MT_PO> getMT(@RequestBody Map<String,String> map) throws Exception {
        log.info("获取-冀北煤炭文件解析,PARAMS:{}",map);
        List<JB_MT_PO> jb_mt_pos = new ArrayList<>();
        try {
            jb_mt_pos = jiBeiMTParseService.parse(map.get("day"));
        } catch (Exception e) {
            log.error("冀北煤炭文件解析失败：原因如下：" + e.getMessage(),e);
            throw new Exception("冀北煤炭文件解析失败");
        }
        log.info("获取-冀北煤炭文件解析成功,返回数据：{}", JSON.toJSONString(jb_mt_pos));
        return jb_mt_pos;
    }

    @ApiOperation("冀北火电上下限文件解析")
    @RequestMapping(value = "/getFireLimit", produces = "application/json; charset=utf-8", method = RequestMethod.POST)
    public List<FireLimitPO> getFireLimit(@RequestBody Map<String,String> map) throws Exception {
        log.info("获取-冀北火电上下限文件解析,PARAMS:{}",map);
        List<FireLimitPO> jbpos = new ArrayList<>();
        try {
            jbpos = jiBeiMTParseService.getFireLimit();
        } catch (Exception e) {
            log.error("冀北火电上下限文件解析失败：原因如下：" + e.getMessage(),e);
            throw new Exception("冀北火电上下限文件解析失败");
        }
        log.info("获取-冀北火电上下限文件解析成功,返回数据：{}", JSON.toJSONString(jbpos));
        return jbpos;
    }




}
